<?php
namespace App\library\services;


use Firebase\JWT\JWT as JwtVendor;
use Illuminate\Http\Request;

class Jwt
{
    /**
     * Author:Yingbo Sun
     * 生成token
     * @param $uid
     * @return mixed
     */
    public static function signToken($uid)
    {
        $key = 'ffdsfsd@4_45'; //key
        $time = time(); //当前时间
        $token = [
            'iss' => '', //签发者 可选
            'aud' => '', //接收该JWT的一方，可选
            'iat' => $time, //签发时间
            'nbf' => $time + 5, //某个时间点后才能访问，比如设置time+30，表示当前时间30秒后才能使用
            'exp' => $time+7200, //过期时间,这里设置2个小时
            'data' => [ //自定义信息
                'userid' => $uid,
            ]
        ];
        $jwt['token'] = JwtVendor::encode($token, $key); //输出Token
        $jwt['expire'] = time() + 7000;
        return $jwt;
    }

    /**
     * Author:Yingbo Sun
     * 验证token
     * @param $token
     * @return int[]
     */
    public static function verification($token)
    {
        $key = 'ffdsfsd@4_45'; //key要和签发的时候一样
        $status = array("code" => 2);
        try {
            JwtVendor::$leeway = 60;//当前时间减去60，把时间留点余地
            $decoded = JwtVendor::decode($token, $key, ['HS256']); //HS256方式，这里要和签发的时候对应
            $arr = (array)$decoded;
            $res['code'] = 1;
            $res['data'] = $arr['data'];
            return $res;
        } catch(\Firebase\JWT\SignatureInvalidException $e) {  //签名不正确
            $status['message'] = "签名不正确";
            return  $status;
        }catch(\Firebase\JWT\BeforeValidException $e) {  // 签名在某个时间点之后才能用
            $status['message'] = "签名在某个时间点之后才能用";
            return  $status;
        }catch(\Firebase\JWT\ExpiredException $e) {  // token过期
            $status['message'] = "token过期";
            return $status;
        }catch(\Exception $e) {  //其他错误
            $status['message'] = "其他错误";
            return $status;
        }

    }

    /**
     * Author:Yingbo Sun
     * 刷新token
     * @param $token
     * @return array
     */
    public static function refreshToken($uid)
    {
        $token = self::signToken($uid);
        return ['code' => 200, 'data' => $token, 'message' => '刷新成功'];
    }
}
